package com.kkd.kkdapp.activity;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.kkd.kkdapp.BaseApplication;
import com.kkd.kkdapp.R;
import com.kkd.kkdapp.Notify.Const;
import com.kkd.kkdapp.Notify.NotifyDispatcher;
import com.kkd.kkdapp.base.BaseActivity;
import com.kkd.kkdapp.db.app.model.User;
import com.kkd.kkdapp.db.user.KkdDBHelper;
import com.kkd.kkdapp.http.entity.LogCard;
import com.kkd.kkdapp.http.entity.Login;
import com.kkd.kkdapp.http.entity.LoginData;

import com.kkd.kkdapp.http.manager.HttpCallBack;
import com.kkd.kkdapp.http.manager.KkdHttpMagager;
import com.kkd.kkdapp.patternlock.PatternLockUtils;
import com.kkd.kkdapp.utils.AppUtil;
import com.kkd.kkdapp.utils.DialogUtils;
import com.kkd.kkdapp.utils.LogUtil;
import com.kkd.kkdapp.utils.PreferenceUtils;
import com.kkd.kkdapp.utils.SystemUtils;

/**
 * 登陆
 * 
 * @author mty
 */
public class LoginActivity extends BaseActivity implements OnClickListener,
		OnFocusChangeListener {

	public static final int TO_LOGIN = 10085;
	public static final int LOGIN_SUCCESS = 10086;
	public static final int LOGIN_CANCLE = 10087;
	private static final int ON_SUCCESS = 1;
	private static final int ON_FAILURE = 2;

	private TextView login_tv; // 快速注册
	private Button login_button; // 登陆按钮
	private RelativeLayout login_title_img; // 返回按钮
	private EditText phonenumber_ed; // 用户名
	private EditText login_pd_ed; // 用户密码
	private TextView mResetPsw; // 忘记密码
	private RelativeLayout phonenumber_img; // 删除
	private String phone;
	private RelativeLayout password_img; // 密码可见性
	private String password;
	private RelativeLayout password_delete;
	private boolean LOGOINFLAG = true;
	private ImageView mEye;
	private String desc;
	private Dialog loadDialog;
	private boolean gesture;
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case ON_SUCCESS:
				// PatternLockUtils.clearPattern(LoginActivity.this);
				startActivity(new Intent(LoginActivity.this,
						GestureEditActivity.class));
				PreferenceUtils.getInstance().setLoginSuccess(
						LoginActivity.this, true);
				if (loadDialog != null) {
					loadDialog.dismiss();
				}
				if (gesture) {
					Intent intent = new Intent(LoginActivity.this,
							HomeActivity.class);
					intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
				} else {
					setResult(LOGIN_SUCCESS);
					finish();
				}
				break;
			case ON_FAILURE:
				showToast(desc);
				if (loadDialog != null) {
					loadDialog.dismiss();
				}
				break;
			case Const.NOTIFY_REGISTER_SUCCESS:
				finish();
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		mTintManager.setTintColor(0x00000000);
		initView();
		setListener();
		NotifyDispatcher.getInstance().registerNotifyHandler(handler);
	}

	/**
	 * 初始化控件
	 */
	public void initView() {
		login_tv = (TextView) this.findViewById(R.id.login_tv);
		login_button = (Button) this.findViewById(R.id.login_button);
		login_title_img = (RelativeLayout) findViewById(R.id.login_title_img);
		phonenumber_ed = (EditText) this.findViewById(R.id.phonenumber_ed);
		login_pd_ed = (EditText) this.findViewById(R.id.login_pd_ed);
		mResetPsw = (TextView) findViewById(R.id.reset_psw);
		phonenumber_img = (RelativeLayout) this
				.findViewById(R.id.phonenumber_img);
		password_img = (RelativeLayout) this.findViewById(R.id.password_img);
		password_delete = (RelativeLayout) this
				.findViewById(R.id.password_delete);
		mEye = (ImageView) this.findViewById(R.id.eye);
		gesture = this.getIntent().getBooleanExtra("gesture", false);
	}

	/**
	 * 注册监听
	 */
	public void setListener() {
		login_tv.setOnClickListener(this);
		login_button.setOnClickListener(this);
		login_title_img.setOnClickListener(this);
		mResetPsw.setOnClickListener(this);
		phonenumber_ed.setOnFocusChangeListener(this);
		phonenumber_img.setOnClickListener(this);
		password_img.setOnClickListener(this);
		password_delete.setOnClickListener(this);
		login_pd_ed.setOnFocusChangeListener(this);
		phonenumber_ed.addTextChangedListener(new TextWatcher() {

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				phone = phonenumber_ed.getText().toString();
				if (!"".equals(phone)) {
					phonenumber_img.setVisibility(View.VISIBLE);
				} else {
					phonenumber_img.setVisibility(View.INVISIBLE);
				}
			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});

		login_pd_ed.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				password = login_pd_ed.getText().toString();
				if (!"".equals(password)) {
					password_delete.setVisibility(View.VISIBLE);
				} else {
					password_delete.setVisibility(View.INVISIBLE);
				}

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});
		login_pd_ed.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_DONE) {
					String str = stringFilter(phonenumber_ed.getText()
							.toString()); // 过滤特殊字符

					if (TextUtils.isEmpty(str)) {
						showToast(R.string.loginactivity_userName);
					} else if ("".equals(login_pd_ed.getText().toString())) {
						showToast(R.string.loginactivity_password);
					} else {
						if (login_pd_ed.length() >= 6) {
							login();
						} else {
							showToast(R.string.password_lenght);
						}

					}

				}
				return false;
			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();
		String phone = PreferenceUtils.getInstance().getPhone(this);
		if (!"".equals(phone)) {
			phonenumber_ed.setText(phone);
			phonenumber_ed.setSelection(phonenumber_ed.getText().toString()
					.length());
		}

	}
	
	@Override
	protected void onDestroy() {
		NotifyDispatcher.getInstance().unRegisterNotifyHandler(handler);
		if (loadDialog != null) {
			loadDialog.cancel();
			loadDialog = null;
		}
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		case R.id.login_tv:// 快速注册
			intent = new Intent(this, RegisterActivity.class);
			startActivity(intent);
			break;
		case R.id.login_button: // 登陆按钮
			String str = stringFilter(phonenumber_ed.getText().toString()); // 过滤特殊字符
			if (LOGOINFLAG) {
				LOGOINFLAG = false;
				handler.postDelayed(new Runnable() {

					@Override
					public void run() {
						LOGOINFLAG = true;
					}
				}, 2000);
				if ("".equals(str)) {
					showToast(R.string.loginactivity_userName);
				} else if ("".equals(login_pd_ed.getText().toString())) {
					showToast(R.string.loginactivity_password);
				} else {
					if (login_pd_ed.length() >= 6) {
						login();
					} else {
						showToast(R.string.password_lenght);
					}

				}
			}

			break;
		case R.id.login_title_img: // 返回按钮
			if (gesture) {
				intent = new Intent(this, HomeActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
			} else {
				setResult(LOGIN_CANCLE);
				finish();
			}
			break;
		case R.id.reset_psw: // 忘记密码
			intent = new Intent(this, ResetPswStepActivity.class);
			intent.putExtra("fixed", false);
			startActivity(intent);
			break;
		case R.id.phonenumber_img:
			if (!"".equals(phone)) {
				phonenumber_ed.setText("");
				phonenumber_img.setVisibility(View.INVISIBLE);
			}
			break;
		case R.id.password_img:
			int inputback = login_pd_ed.getInputType();
			if (inputback == 145) {
				mEye.setImageResource(R.drawable.login_password);
				login_pd_ed.setInputType(129);
				login_pd_ed.setSelection(login_pd_ed.getText().toString()
						.length());
			} else if (inputback == 129) {
				mEye.setImageResource(R.drawable.login_password_visible);
				login_pd_ed.setInputType(145);
				login_pd_ed.setSelection(login_pd_ed.getText().toString()
						.length());
			}
			LogUtil.e("inputback", "" + inputback);
			break;
		case R.id.password_delete:
			if (!"".equals(password)) {
				login_pd_ed.setText("");
				password_delete.setVisibility(View.INVISIBLE);
			}
			break;

		}

	}

	public static String stringFilter(String str) throws PatternSyntaxException {
		String regEx = "[/\\-;:*?#<>+,|\"\n\t]";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		return m.replaceAll("");
	}

	@Override
	public void onFocusChange(View v, boolean hasFocus) {

		switch (v.getId()) {
		case R.id.login_pd_ed:
			if (hasFocus) {
				password = login_pd_ed.getText().toString();
				if (!"".equals(password)) {
					password_delete.setVisibility(View.VISIBLE);
				}
			} else {
				password_delete.setVisibility(View.INVISIBLE);
			}
			break;
		case R.id.phonenumber_ed:
			if (hasFocus) {
				phone = phonenumber_ed.getText().toString();
				if (!"".equals(phone)) {
					phonenumber_img.setVisibility(View.VISIBLE);
				}
			} else {
				phonenumber_img.setVisibility(View.INVISIBLE);
			}
			break;
		}

	}

	public void login() {
		if (loadDialog != null) {
			loadDialog.cancel();
			loadDialog = null;
		}
		loadDialog = DialogUtils.toLoadDialog(this, "登录中...");
		KkdHttpMagager.getInstance().getLoginManager(
				phonenumber_ed.getText().toString(),
				login_pd_ed.getText().toString(), Login.class,
				new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object res) {

						handler.sendEmptyMessage(ON_SUCCESS);
					}

					@Override
					public void onFailure(int statusCode, String responseBody) {

						desc = responseBody;
						handler.sendEmptyMessage(ON_FAILURE);
					}
				});

	}

}
